import { openDB } from 'idb';

const dbPromise = openDB('my-cache-db', 1, {
  upgrade(db) {
    if (!db.objectStoreNames.contains('cache')) {
      db.createObjectStore('cache');
    }
  },
});

/**
 * 获取缓存
 * @param {string} key
 * @returns {Promise<any>}
 */
export async function getCache(key) {
  return (await dbPromise).get('cache', key);
}

/**
 * 保存缓存
 * @param {string} key
 * @param {any} data
 * @returns {Promise<void>}
 */
export async function saveCache(key, data) {
  return (await dbPromise).put('cache', data, key);
}

/**
 * 删除缓存
 * @param {string} key
 * @returns {Promise<void>}
 */
export async function removeCache(key) {
  return (await dbPromise).delete('cache', key);
}
